package ;

import flash.events.KeyboardEvent;
import flash.text.TextField;
import hxm.monads.FutureMonad;

/**
 * ...
 * @author Simon Krajewski
 */

class FlashIO 
{
	static public var init =
	{
		output = new TextField();
		output.width = 400;
		output.height = 300;
		output.border = true;
		output.multiline = true;
		flash.Lib.current.addChild(output);
		
		input = new TextField();
		input.width = 400;
		input.height = 20;
		input.border = true;
		input.multiline = false;
		input.type = flash.text.TextFieldType.INPUT;
		input.y = output.height;
		flash.Lib.current.addChild(input);
		input.addEventListener(KeyboardEvent.KEY_DOWN, onKeyDown);
		null;
	}
	
	static public var output:TextField;
	static public var input:TextField;
	
	static var listeningFutures:Array<Future<String>> = new Array();
	
	static public function putLine(line)
	{
		output.text += line +"\n";
	}
	
	static public function getLine():Future<String>
	{
		var future = new Future(null);
		listeningFutures.push(future);
		return future;
	}
	
	static private function onKeyDown(e:KeyboardEvent):Void 
	{
		if (e.keyCode != 13)
			return;
		if (listeningFutures.length == 0)
			return;
		listeningFutures.pop().complete(input.text);
		input.text = "";
	}
}